//
//  ZLItemReuseStackView.m
//  ZLCocoaKit_Example
//
//  Created by Dev on 2024/12/5.
//  Copyright © 2024 itzhaolei. All rights reserved.
//

#import "ZLItemReuseStackView.h"
#import <ReactiveObjC/ReactiveObjC.h>

@interface ZLItemReuseStackView()

@end

@implementation ZLItemReuseStackView

- (void)addArrangedSubview:(UIView *)view {
    [super addArrangedSubview:view];
    // 监听显示隐藏
    __weak typeof(self)weakSelf = self;
    [RACObserve(view, hidden) subscribeNext:^(id  _Nullable x) {
        weakSelf.viewCount = [weakSelf.arrangedSubviews.rac_sequence filter:^BOOL(UIView * _Nullable thisView) {
            return !thisView.hidden;
        }].array.count;
    }];
    [[view rac_signalForSelector:@selector(removeFromSuperview)] subscribeNext:^(RACTuple * _Nullable x) {
        weakSelf.viewCount = [weakSelf.arrangedSubviews.rac_sequence filter:^BOOL(UIView * _Nullable thisView) {
            return !thisView.hidden;
        }].array.count;
    }];
}

#pragma mark - Public
- (void)setItemCount:(NSInteger)itemCount init:(UIView *(^)(NSInteger index))init fillData:(void(^ _Nullable)(UIView *view, NSInteger index))fillData {
    NSInteger maxCount = itemCount > self.arrangedSubviews.count ? itemCount : self.arrangedSubviews.count;
    for (NSInteger index = 0; index < maxCount; index++) {
        // 获取控件
        UIView *view = nil;
        if (index < self.arrangedSubviews.count) {
            view = self.arrangedSubviews[index];
        }else {
            // 创建控件
            view = init(index);
            [self addArrangedSubview:view];
        }
        // 控制控件的显示隐藏
        view.hidden = index >= itemCount;
        // 赋值
        if (index < itemCount) {
            if (fillData) {
                fillData(view, index);
            }
        }
    }
}
#pragma mark - Public
- (void)setItemCount:(NSInteger)itemCount init:(UIView *(^)(NSInteger index))init {
    [self setItemCount:itemCount init:init fillData:nil];
}

@end
